package net.neiquan.applibrary.numberpicker.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils
{

    /**
     * 从assets中读取文本
     *
     * @param name
     * @return
     */
    public static String readFileFromAssets(Context context, String name) {
        InputStream is = null;
        try {
            is = context.getResources().getAssets().open(name);
        } catch (Exception e) {
            throw new RuntimeException(FileUtils.class.getName()
                    + ".readFileFromAssets---->" + name + " not found");
        }
        return inputStream2String(is);
    }

    /**
     * 输入流转字符串
     *
     * @param is
     * @return 一个流中的字符串
     */
    public static String inputStream2String(InputStream is) {
        if (null == is) {
            return null;
        }
        StringBuilder resultSb = null;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            resultSb = new StringBuilder();
            String len;
            while (null != (len = br.readLine())) {
                resultSb.append(len);
            }
        } catch (Exception ex) {
        } finally {
            closeIO(is);
        }
        return null == resultSb ? null : resultSb.toString();
    }
    /**
     * 关闭流
     *
     * @param closeables
     */
    private static void closeIO(Closeable... closeables) {
        if (null == closeables || closeables.length <= 0) {
            return;
        }
        for (Closeable cb : closeables) {
            try {
                if (null == cb) {
                    continue;
                }
                cb.close();
            } catch (IOException e) {
                throw new RuntimeException(
                        FileUtils.class.getClass().getName(), e);
            }
        }
    }

    public static void compresFileByQuality(String path,OnFileCompressListener onFileCompressListener) {
        try {
            FileInputStream is = new FileInputStream(path);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int quality = 100;
            Log.e("result111",baos.toByteArray().length+"==============");
            while (baos.toByteArray().length / 1024 > 4*1024) { // 循环判断如果压缩后图片是否大于4M,大于继续压缩
                baos.reset();// 重置baos即清空baos
                quality -= 10;// 每次都减少10
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);// 这里压缩quality%，把压缩后的数据存放到baos中
            }
            Log.e("result222",baos.toByteArray().length+"==============");
            SimpleDateFormat format = new SimpleDateFormat("yyyymmddhhmmss");
            Date date = new Date(System.currentTimeMillis());
            String filename = format.format(date);
            File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
            if (null != bitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            onFileCompressListener.onFileSuccess(file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            onFileCompressListener.onFileFail(e.getMessage());
        }
    }

    public interface OnFileCompressListener{
        void onFileSuccess(String path);
        void onFileFail(String reason);
    }
}
